package com.gupao.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @基本功能:
 * @program:gupao-netty
 * @author: jiawy
 * @create:2024-10-10 19:32:38
 **/
public class NewIOServerT {

    static Selector selector;
    public static void main(String[] args) throws Exception {

        selector = Selector.open();

        ServerSocketChannel serverSocketChannel= ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        serverSocketChannel.register(selector , SelectionKey.OP_ACCEPT);
        while (true) {

            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {

                    handlerAccept(key);
                } else if (key.isReadable()) {

                    handlerRead(key);
                } else if(key.isWritable()){
                    handlerWrite(key);
                }

            }
        }
    }

    private static void handlerWrite(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        socketChannel.write(ByteBuffer.wrap("helloREWREWREWR".getBytes()));
    }

    private static void handlerRead(SelectionKey selectionKey) throws IOException {
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer allocate = ByteBuffer.allocate(1024);

        socketChannel.read(allocate);

        System.out.println("server msg:" + new String(allocate.array()));
        socketChannel.register(selector , SelectionKey.OP_WRITE);
    }

    private static void handlerAccept(SelectionKey selectionKey) throws IOException {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();

        SocketChannel socketChannel = serverSocketChannel.accept();
        socketChannel.configureBlocking(false);
        socketChannel.write(ByteBuffer.wrap("I am wentai,is shuai".getBytes()));
        socketChannel.register(selector , SelectionKey.OP_READ);
    }
}